package com.ruoyi.business.service.impl;

import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.business.Dto.BusGradeTeacherDto;
import com.ruoyi.business.Dto.GradeTeacherHistory;
import com.ruoyi.business.domain.*;
import com.ruoyi.business.mapper.BusGradeTeacherMapper;
import com.ruoyi.business.service.*;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 班级教师Service业务层处理
 * 
 * @author ruoyi
 * @date 2022-10-22
 */
@Service
public class BusGradeTeacherServiceImpl extends ServiceImpl<BusGradeTeacherMapper,BusGradeTeacher> implements IBusGradeTeacherService
{
    @Autowired
    private BusGradeTeacherMapper busGradeTeacherMapper;
    //班级
    @Autowired
    private IBusGradeService busGradeService;
    //课程
    @Autowired
    private IBusSubjectService busSubjectService;
    //用户表
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private IBusSemesterService semesterService;

    @Autowired
    private IPostService sysPostService;



    @Autowired
    private IUserPostService userPostService;

    @Override
    public List<BusGradeTeacherDto> selectBusGradeTeacherDto() {
        //先获取所有的教师
        List<BusGradeTeacher> list = this.list();
        //存储已经聚合的教师
        Map<Long,BusGradeTeacherDto> ListTeacherDto=new HashMap<>();
        //通过流的方式复写列表中所有老师的信息
        for (BusGradeTeacher x:list) {
            //拿一个用户ID
            Long userId = x.getUserId();
            //再拿一个班级ID
            Long gradeId = x.getGradeId();
            //获取该教师的课程ID
            Long subjectID = x.getSubjectId();
            //封装的对象
            BusGradeTeacherDto busGradeTeacherDto;
            if (!ListTeacherDto.containsKey(userId)) {
                busGradeTeacherDto=new BusGradeTeacherDto();
            }else {
                busGradeTeacherDto=ListTeacherDto.get(userId);
            }
            //封装教师信息
            BeanUtils.copyProperties(x,busGradeTeacherDto);
            //获取用户的信息
            SysUser sysUser = sysUserService.selectUserById(userId);

            BeanUtils.copyProperties(sysUser,busGradeTeacherDto);
            //获取课程名称
            LambdaQueryWrapper<BusSubject> subjectLambdaQueryWrapper=new LambdaQueryWrapper<>();
            subjectLambdaQueryWrapper.eq(BusSubject::getSubjectId,subjectID);
            BusSubject subject = busSubjectService.getOne(subjectLambdaQueryWrapper);
            //建立班级的筛选器
            LambdaQueryWrapper<BusGrade> gradeLambdaQueryWrapper=new LambdaQueryWrapper<>();
            //用来查到这个老师对应的班级
            gradeLambdaQueryWrapper.eq(gradeId!=null,BusGrade::getGradeId,gradeId);
            //一个老师对象对应的教学班级
            List<BusGrade> grades = busGradeService.list(gradeLambdaQueryWrapper);
            /**
             * 判断是否为某班的班主任，并且将这个老师对应这个班级所受课程封装
             */
//            List<BusGrade> busGradeList=new ArrayList<>();
            for (BusGrade grade:grades) {
                //判断是否为班主任
                if (grade.getUserId().equals(userId)){
                    //所带的班级
                    busGradeTeacherDto.addBusGrade(grade.getGradeId());
                    //确认是班主任
                    busGradeTeacherDto.setHeadTeacher(true);
                    //设置班级名
                    busGradeTeacherDto.setGradeName(grade.getGradeName());
                }
                //班级对应课程，以map封装
                busGradeTeacherDto.setClassWithSubject(grade.getGradeName(),subjectID+"");
            }
            //存放到数组中
            ListTeacherDto.put(userId,busGradeTeacherDto);
        }
        //等循环完以后把所有的map中聚合过的value都拿出来
        Collection<BusGradeTeacherDto> values = ListTeacherDto.values();
        List<BusGradeTeacherDto> busGradeTeacherDtos=new ArrayList<>(values);
        return busGradeTeacherDtos;
    }

    @Override
    public boolean removeBusGradeTeacherDto(Long userId) {
        LambdaQueryWrapper<BusGradeTeacher> teacherLambdaQueryWrapper=new LambdaQueryWrapper<>();
        teacherLambdaQueryWrapper.eq(userId!=null,BusGradeTeacher::getUserId,userId);
        boolean remove = this.remove(teacherLambdaQueryWrapper);
        return remove;
    }

    /**
     * 查询班级教师
     * 
     * @param gradeId 班级教师主键
     * @return 班级教师
     */
    @Override
    public BusGradeTeacher selectBusGradeTeacherByGradeId(Long gradeId)
    {
        return busGradeTeacherMapper.selectBusGradeTeacherByGradeId(gradeId);
    }

    /**
     * 查询班级教师列表
     * 
     * @param busGradeTeacher 班级教师
     * @return 班级教师
     */
    @Override
    public List<BusGradeTeacher> selectBusGradeTeacherList(BusGradeTeacher busGradeTeacher)
    {
        return busGradeTeacherMapper.selectBusGradeTeacherList(busGradeTeacher);
    }

    /**
     * 新增班级教师
     * 
     * @param busGradeTeacher 班级教师
     * @return 结果
     */
    @Override
    public int insertBusGradeTeacher(BusGradeTeacher busGradeTeacher)
    {
        return busGradeTeacherMapper.insertBusGradeTeacher(busGradeTeacher);
    }

    /**
     * 修改班级教师
     * 
     * @param busGradeTeacher 班级教师
     * @return 结果
     */
    @Override
    public int updateBusGradeTeacher(BusGradeTeacher busGradeTeacher){
        return busGradeTeacherMapper.updateBusGradeTeacher(busGradeTeacher);
    }

    /**
     * 批量删除班级教师
     * 
     * @param gradeIds 需要删除的班级教师主键
     * @return 结果
     */
    @Override
    public int deleteBusGradeTeacherByGradeIds(Long[] gradeIds)
    {
        return busGradeTeacherMapper.deleteBusGradeTeacherByGradeIds(gradeIds);
    }

    /**
     * 删除班级教师信息
     * 
     * @param gradeId 班级教师主键
     * @return 结果
     */
    @Override
    public int deleteBusGradeTeacherByGradeId(Long gradeId)
    {
        return busGradeTeacherMapper.deleteBusGradeTeacherByGradeId(gradeId);
    }


    /**
     * 这个对应科目的所有老师信息
     * @return
     */
    @Override
    public Map<String, List<String>> getPostTeachers() {

        Map<String, List<String>> map = new HashMap<>();

        //取出不是班主任的，科目名字添加到Map的项中
        LambdaQueryWrapper<Post> splqw = new LambdaQueryWrapper<>();
        splqw.ne(Post::getPostId,1L);
        List<Post> list = sysPostService.list(splqw);
        for (Post sysPost : list) {
            String postName = sysPost.getPostName();
            map.put(postName,new ArrayList<>());

            Long postId = sysPost.getPostId();

            LambdaQueryWrapper<UserPost> uplqw = new LambdaQueryWrapper<>();
            uplqw.eq(UserPost::getPostId,postId);
            List<UserPost> list1 = userPostService.list(uplqw);
            for (UserPost userPost : list1) {
                Long userId = userPost.getUserId();

                SysUser sysUser = sysUserService.selectUserById(userId);
                String nickName = sysUser.getNickName();

                List<String> strings = map.get(postName);
                strings.add(nickName);

            }
        }
        return map;
    }




    @Override
    public JSONObject getGradeByUserId(Long userId) {

        List<Map<String,Long>> info = busGradeTeacherMapper.
                getGradeByUserId(userId);

        //返回类
        JSONObject entries = new JSONObject();
        //存储所带班级id
        Set<Long> gradeIds = new HashSet<Long>() {};
        //存储在所带班级中的角色
        HashMap<String, List<Long>> stringLongHashMap = new HashMap<>();
        info.forEach((item)->{
            Long gradeId = item.get("grade_id");
            gradeIds.add(gradeId);
            stringLongHashMap.computeIfAbsent(gradeId.toString(),
                    k -> new ArrayList<>());
            stringLongHashMap.get(gradeId.toString()).
                    add(item.get("post_id"));




        });
        entries.set("code",200);
        entries.set("data",gradeIds);
        entries.set("postId",stringLongHashMap);
        return entries;
    }

    @Override
    public Set<GradeTeacherHistory> getHistoryGradeByUserId(Long userId) {
        Set<GradeTeacherHistory> currentGrade= getCurrentGradeByUserId(userId);
        Set<GradeTeacherHistory> historyGrade= busGradeTeacherMapper.getHistoryGradeByUserId(userId);
        historyGrade.addAll(currentGrade);
        return historyGrade;
    }
    @Override
    public Set<GradeTeacherHistory> getCurrentGradeByUserId(Long userId){
        Set<GradeTeacherHistory> currentGrade = busGradeTeacherMapper.getCurrentGradeByUserId(userId);
        Long currentSemesterId = semesterService.getCurrentSemesterId();
        currentGrade.forEach((grade)->{
            grade.setSemesterId(currentSemesterId);
        });
        return currentGrade;
    }

    @Override
    public List<SubjectTeacher> getGradeTeacher(Long gradeId) {
        return busGradeTeacherMapper.getGradeTeacher(gradeId);

    }

    @Override
    public List<Long> getLeadGrade(Long userId) {
        return busGradeTeacherMapper.getLeadGrade(userId);
    }
}
